package fr.geobert.prediction;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

/**
 * This is for AutoCompleteTextView to work, not need for another integration
 * 
 * read LangDbAdapter next
 * @author geob
 *
 */
public class MatchAdapter extends CursorAdapter {

	private LangDbAdapter mDbHelper;
	private String mCurrentConstraint;
	
	public long parentId;
	public int position;
	public String mCurrentWord;
		
	public MatchAdapter(Activity ctx) {
		super(ctx, null);
		
		mDbHelper = LangDbAdapter.getInstance(ctx);
		mDbHelper.open();
	}

	@Override
	public CharSequence convertToString(Cursor cursor) {
		return cursor.getString(3);
	}
	
	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		String text = convertToString(cursor).toString();
		((TextView) view).setText(text);
	}
	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		final LayoutInflater inflater = LayoutInflater.from(context);
		final View view = inflater.inflate(
				android.R.layout.simple_dropdown_item_1line, parent, false);

		return view;
	}

	@Override
	public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
		mCurrentConstraint = mCurrentWord != null ? AsciiUtils.convertNonAscii(mCurrentWord.toString()) : null;
		
		if (getFilterQueryProvider() != null) {
			return getFilterQueryProvider().runQuery(mCurrentWord);
		}
		Cursor c = mDbHelper.fetchMatchingInfo(mCurrentConstraint, parentId, position);
		return c;
	}
}
